package com.bestcem.xm.ticket.grpc.client;

import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.ticket.grpc.client.dto.wechat.WechatUserInfoDTO;
import com.bestcem.xm.wechat.grpc.v1.services.*;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import zhongyan.xm.base.v1.Base;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collection;
import java.util.Objects;

/**
 * 微信模块 grpc client 方法
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version 通知提醒新增微信公众号
 * @date 2022/4/13 17:02
 */
@Slf4j
@Service
public class TicketWechatGrpcService {

    @GrpcClient(GrpcClientNames.XM)
    private BpWechatServiceGrpc.BpWechatServiceBlockingStub bpWechatServiceBlockingStub;

    /**
     * 发送微信公众号模板消息
     *
     * @param openIds    接收消息的 微信openId 列表
     * @param templateId 微信公众号模板id
     * @param params     微信公众号模板自定义参数
     * @param url        跳转链接
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2022/4/13 16:59
     */
    public void sendTemplateMessage(@Nonnull Collection<String> openIds, @Nonnull String templateId
            , @Nonnull String params, @Nullable String url) {
        SendTemplateMessageRequest.Builder builder = SendTemplateMessageRequest.newBuilder();
        if (!CollectionUtils.isEmpty(openIds)) {
            builder.addAllOpenIds(openIds);
        }
        builder.setTemplateId(templateId);
        if (!ObjectUtils.isEmpty(params)) {
            builder.setData(params);
        }
        if (!ObjectUtils.isEmpty(url)) {
            builder.setUrl(url);
        }
        try {
            SendTemplateMessageResponse response = bpWechatServiceBlockingStub.sendTemplateMessage(builder.buildPartial());
            if (Objects.isNull(response) || Base.Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[Ticket] WECHAT sendTemplateMessage {}-{}-{}-{} Error; ErrorMsg: {}",
                        openIds, templateId, params, url, response);
            }
        } catch (Exception e) {
            log.error("[Ticket] WECHAT sendTemplateMessage {}-{}-{}-{} Error",
                    openIds, templateId, params, url, e);
        }
    }


    /**
     * 获取微信用户个人信息
     *
     * @param openId 微信openId
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2022/4/13 16:59
     */
    @Nullable
    public WechatUserInfoDTO getWechatUserInfo(@Nonnull String openId) {
        GetWechatUserInfoRequest.Builder builder = GetWechatUserInfoRequest.newBuilder();
        if (ObjectUtils.isEmpty(openId)) {
            return null;
        }
        builder.setOpenId(openId);
        try {
            GetWechatUserInfoResponse response = bpWechatServiceBlockingStub.getWechatUserInfo(builder.buildPartial());
            if (Objects.isNull(response) || Base.Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[Ticket] WECHAT getWechatUserInfo {} Error; ErrorMsg: {}", openId, response);
            }
            return responseToWechatUserInfoDTO(response);
        } catch (Exception e) {
            log.error("[Ticket] WECHAT getWechatUserInfo {} Error", openId, e);
            return null;
        }
    }


    // ============================ private method ============================

    /**
     * GetWechatUserInfoResponse 转 WechatUserInfoDTO
     *
     * @param response GetWechatUserInfoResponse
     * @return WechatUserInfoDTO
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2022/4/13 17:16
     */
    @Nullable
    private static WechatUserInfoDTO responseToWechatUserInfoDTO(GetWechatUserInfoResponse response) {
        if (Objects.isNull(response)) {
            return null;
        }

        WechatUserInfoDTO dto = new WechatUserInfoDTO();
        dto.setNickname(response.getNickname());
        dto.setGender(response.getGender());
        dto.setProvince(response.getProvince());
        dto.setCity(response.getCity());
        dto.setCountry(response.getCountry());
        dto.setHeadImgUrl(response.getHeadImgUrl());
        dto.setPrivilege(response.getPrivilegeList());
        dto.setUnionId(response.getUnionId());
        return dto;
    }
}
